import { ref, reactive, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import {
  getTheLatestMessage,
  queryChatRooms,
  insertChatRooms,
  insertChatRecord,
  updateChatNoMessage,
} from '@/utils/Electron'
import { chatRoomList, allChatRecords, friendsRelationShip, allFriendsRequests, requestMessage } from '@/lib/api'
import { classifyNames } from '@/utils/PinYinUtils'
import type { ChatRecordType } from '@/lib/interfaces'
import useAuthStore from './authStore'
import useChatStore from './chatStore'
import PubSub from 'pubsub-js'
import moment from 'moment'

export type ChatRecordStateType = {
  id: number
  recordList: Array<ChatRecordType>
}

export type currentChatRoomInfoType = {
  id: string
  roomName: string
  avatar: string
}

export default defineStore('room', (store) => {
  const authStore = useAuthStore()
  const chatStore = useChatStore()
  // 定义属性
  const currentChatRoomInfo = ref<currentChatRoomInfoType>({ id: '0', roomName: '', avatar: '' }) // 正在聊天的房间，当前处于哪个房间
  const commentList = ref([]) // 聊天窗口显示的聊天房间

  // 设置聊天房间
  const setCommentList = (list: any) => {
    commentList.value = list
  }

  // 设置当前聊天房间的信息
  const setCurrentChattingRoomInfo = (obj: currentChatRoomInfoType) => {
    currentChatRoomInfo.value.id = obj.id
    currentChatRoomInfo.value.roomName = obj.roomName
    currentChatRoomInfo.value.avatar = obj.avatar
    setRoomNoReadCount(obj.id)
  }

  // 给左侧聊天列表设置最新的消息
  const setTheLatestMessageByRoomId = (currentId: any): void => {
    getTheLatestMessage(currentId).then((res) => {
      const message = res.data.list[0]
      if (message) {
        commentList.value.forEach((item: any) => {
          if (item.roomId == currentId) {
            item.lastMessage = JSON.stringify({
              time: message.time,
              content: message.content
            })
          }
        })
      }
    })
  }

  // 设置房间未读消息数量
  const setRoomNoReadCount = (roomId: string) => {
    // 修改本地数据库的数量
    updateChatNoMessage(roomId, roomId == currentChatRoomInfo.value.id)
    commentList.value.forEach((item: any) => {
      if (item.roomId == roomId) {
        item.noMessage = (roomId == currentChatRoomInfo.value.id ? 0 : item.noMessage+1)
      }
    })
  }

  // 获取本地的聊天房间
  const getLocalChatRooms = (userInfo: any) => {
    queryChatRooms(userInfo.userId).then((res: any) => {
      // 将聊天数据放入Pinia中
      if (res.data.list || res.data.list.length > 0) {
        const firstChatRoom = res.data.list[0]
        // 注入聊天房间
        setCommentList(
          res.data.list.map((item: any) => ({
            ...item,
            id: item.roomId,
            lastMessage: item.lastMessage || {}
          }))
        )
        if(firstChatRoom) {
          // 注入当前聊天房间信息
          setCurrentChattingRoomInfo({
            id: firstChatRoom.roomId,
            roomName: firstChatRoom.name,
            avatar: firstChatRoom.avatar
          })
        }
      }
    })
  }

  // 同步服务端所有的聊天房间
  const getRemoteChatRooms = (insert = false) => {
    const userInfo = authStore.userInfo
    return chatRoomList().then((res: any) => {
      if (res.code === 0) {
        const firstChatRoom = res.data.list[0]
        // chatStore.stateSync()
        // 注入Pinia聊天房间数据
        setCommentList(
          res.data.list.map((item: any) => ({
            ...item,
            roomId: item.id,
            lastMessage: ''
          }))
        )
        if(firstChatRoom) {
          // 注入聊天房间的聊天数据
          setCurrentChattingRoomInfo({
            id: firstChatRoom.id,
            roomName: firstChatRoom.name,
            avatar: firstChatRoom.avatar
          })
        }
        if (insert && res.data.list.length > 0) {
          // 将房间插入本地数据库
          insertChatRooms(
            res.data.list.map((item: any) => ({
              ...item,
              username: userInfo.userName,
              lastMessage: JSON.stringify(item.lastMessage || {})
            })),
            userInfo.userId
          )
        }
      }
    })
  }

  /**
   * 插入新房间
   * @param roomId 
   */
  const addChatRoomWithMessage = (roomInfo: any, message: any) => {
    const userInfo = authStore.userInfo
    const list = [roomInfo]
    // 把新房间插入到SQLlite中（插入消息时会判断是否有当前这条消息）
    insertChatRooms(
      list.map((item: any) => ({
        ...item,
        lastMessage: JSON.stringify({time: moment().format('YYYY-MM-DD HH:mm:ss'), content: message.content}),
        noMessage: 1
      })),
      userInfo.userId
    )
    Object.assign(message, {time: moment().format('YYYY-MM-DD HH:mm:ss'), content: message.message})
    // 将新房间放到Pinia中并且是第一位
    Object.assign(roomInfo, {roomId: roomInfo.id,lastMessage: JSON.stringify(message), noMessage: 1})
    commentList.value.unshift(roomInfo)
    // 将聊天数据放入SQLite
    insertChatRecord(message)
    // 将聊天数据放入Pinia中
    const index = chatStore.chatRecordList.findIndex(
      (item) => item.id === roomInfo.id
    )
    if(index==-1) {
      // 设置聊天记录
      chatStore.chatRecordList.push({
        id: roomInfo.id,
        recordList: []
      })
    } else {
      chatStore.chatRecordList[index].recordList.push(message)
    }
  }


  const resetStore = () => {
    currentChatRoomInfo.value =({ id: '0', roomName: '', avatar: '' })
    commentList.value = []
  }

  return {
    commentList,
    currentChatRoomInfo,
    getRemoteChatRooms,
    setCurrentChattingRoomInfo,
    setTheLatestMessageByRoomId,
    setCommentList,
    addChatRoomWithMessage,
    setRoomNoReadCount,
    getLocalChatRooms,
    resetStore
  }
})
